package com.zzyl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.vo.DeviceVo;
import com.zzyl.websocket.WebSocketServer;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class AmqpClient implements ApplicationRunner {
    private final static Logger logger = LoggerFactory.getLogger(AmqpClient.class);

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。
    //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
    private static String clientId;

    static {
        try {
            clientId = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    // 指定单个进程启动的连接数
    // 单个连接消费速率有限，请参考使用限制，最大64个连接
    // 连接数和消费速率及rebalance相关，建议每500QPS增加一个连接
    private static int connectionCount = 64;

    //业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
    @Autowired
    private ExecutorService executorService;

    public void start() throws Exception {
        List<Connection> connections = new ArrayList<>();

        //参数说明，请参见AMQP客户端接入说明文档。
        for (int i = 0; i < connectionCount; i++) {
            long timeStamp = System.currentTimeMillis();
            //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
            String signMethod = "hmacsha1";

            //userName组装方法，请参见AMQP客户端接入说明文档。
            String userName = clientId + "-" + i + "|authMode=aksign"
                    + ",signMethod=" + signMethod
                    + ",timestamp=" + timeStamp
                    + ",authId=" + aliIoTConfigProperties.getAccessKeyId()
                    + ",iotInstanceId=" + aliIoTConfigProperties.getIotInstanceId()
                    + ",consumerGroupId=" + aliIoTConfigProperties.getConsumerGroupId()
                    + "|";
            //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
            String signContent = "authId=" + aliIoTConfigProperties.getAccessKeyId() + "&timestamp=" + timeStamp;
            String password = doSign(signContent, aliIoTConfigProperties.getAccessKeySecret(), signMethod);
            String connectionUrl = "failover:(amqps://" + aliIoTConfigProperties.getHost() + ":5671?amqp.idleTimeout=80000)"
                    + "?failover.reconnectDelay=30";

            Hashtable<String, String> hashtable = new Hashtable<>();
            hashtable.put("connectionfactory.SBCF", connectionUrl);
            hashtable.put("queue.QUEUE", "default");
            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
            Context context = new InitialContext(hashtable);
            ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
            Destination queue = (Destination) context.lookup("QUEUE");
            // 创建连接。
            Connection connection = cf.createConnection(userName, password);
            connections.add(connection);

            ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
            // 创建会话。
            // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
            // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            connection.start();
            // 创建Receiver连接。
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(messageListener);
        }

        logger.info("amqp  is started successfully, and will exit after server shutdown ");
    }

    private MessageListener messageListener = message -> {
        try {
            //异步处理收到的消息，确保onMessage函数里没有耗时逻辑
            executorService.submit(() -> processMessage(message));
        } catch (Exception e) {
            logger.error("submit task occurs exception ", e);
        }
    };

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private void processMessage(Message message) {
        try {
            byte[] body = message.getBody(byte[].class);
            String contentStr = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            logger.info("receive message"
                    + ",\n topic = " + topic
                    + ",\n messageId = " + messageId
                    + ",\n content = " + contentStr);
            //保存设备数据
            Content content = JSONUtil.toBean(contentStr, Content.class);
            //查询设备数据
            List<DeviceVo> deviceVos = deviceMapper.selectByDeviceIds(Arrays.asList(content.getIotId()));
            if(CollectionUtil.isEmpty(deviceVos)){
                logger.error("设备数据为空，IotId:{}",content.getIotId());
                return;
            }

            DeviceVo deviceVo = deviceVos.get(0);

            List<DeviceDataVo> deviceDataVos = new ArrayList<>();

            //保存设备数据
            content.getItems().forEach((key,item)->{

                //过滤数据是否触发报警
                Integer status = alertFilter(key,item,content);

                DeviceData deviceData = DeviceData.builder()
                        .alarmTime(LocalDateTimeUtil.of(item.getTime()))
                        .functionName(key)
                        .dataValue(item.getValue()+"")
                        .deviceName(content.getDeviceName())
                        .productId(content.getProductKey())
                        .iotId(content.getIotId())
                        .status(status+"")
                        .noteName(deviceVos.get(0).getNickname())
                        .productName(deviceVos.get(0).getProductName())
                        .build();

                deviceDataMapper.insert(deviceData);
                DeviceDataVo deviceDataVo = BeanUtil.toBean(deviceData, DeviceDataVo.class);
                deviceDataVos.add(deviceDataVo);

                //状态为2，推送到数据（楼层）到前端，进行提醒
                if(status.equals(2) && deviceVo.getLocationType().equals(1)){

                    String floor = deviceVo.getDeviceDescription().split(",")[0];
                    try {
                        webSocketServer.sendMessageToAll(floor);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            });
            //大key:deviceData  小key:设备id  数据：物模型列表deviceDataVos
            redisTemplate.opsForHash().put(Constants.DEVICE_LASTDATA_CACHE_KEY,content.getIotId(),JSONUtil.toJsonStr(deviceDataVos));

        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 过滤数据是否触发报警
     * @param key   物模型key
     * @param item  物模型数据（value,time）
     * @param content  接收的数据，获取产品和设备数据
     * @return
     */
    private Integer alertFilter(String key, Content.Item item, Content content) {

        //线程安全的类，包装了Integer  线程可见的，更安全
        //状态值：0  正常   1 异常    2 待处理
        AtomicInteger finalStatus = new AtomicInteger(0);

        //查询报警规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(key, "-1", content.getProductKey());
        if(CollectionUtil.isEmpty(alertRules)){
            return finalStatus.get();
        }
        //遍历规则
        alertRules.forEach(alertRule -> {

            int status = 0;

            //判断是否在生效时段内
            String[] aepArr = alertRule.getAlertEffectivePeriod().split("~");
            LocalTime startTime = LocalTime.parse(aepArr[0]);
            LocalTime endTime = LocalTime.parse(aepArr[1]);
            //上报时间
            LocalTime time = LocalDateTimeUtil.of(item.getTime()).toLocalTime();
            //开始时间8
            //结束时间10
            //上报时间 9
            if(startTime.isAfter(time) || endTime.isBefore(time)){
                return;
            }
            //操作符  阈值 上报的值
            //val如果小于0  左边小于右边
            //val等于0  左边与右边相等
            //val如果大于0  左边大于右边
            int val = alertRule.getValue().compareTo((float) item.getValue());
            if(alertRule.getOperator().equals(">=") && val <= 0){
                status = 1;
                finalStatus.set(1);
            }

            if(alertRule.getOperator().equals("<") && val > 0){
                status = 1;
                finalStatus.set(1);
            }

            //设备id
            String deviceId = content.getIotId();
            //从redis中获取数据
            String aggCountKey = alertRule.getId()+"_"+deviceId+"_"+key+"_aggregation";
            String aggTimeKey = "aggregation_"+alertRule.getId()+"_"+deviceId+"_"+key;



            //正常数据
            if(status == 0){
                redisTemplate.delete(aggCountKey);
                redisTemplate.delete(aggTimeKey);
                return;
            }

            //获取沉默周期数据
            String silentCacheKey = "silent_"+alertRule.getId()+"_"+deviceId+"_"+key;
            String silentData = redisTemplate.opsForValue().get(silentCacheKey);
            if(StringUtils.isNotEmpty(silentData)){
                return;
            }

            //获取redis中的数据
            String aggCountData = redisTemplate.opsForValue().get(aggCountKey);
            String aggTimeData = redisTemplate.opsForValue().get(aggTimeKey);
            if(StringUtils.isEmpty(aggCountData) || StringUtils.isEmpty(aggTimeData)){

                //并且 持续周期为1
                if(alertRule.getDuration().equals(1)){
                    finalStatus.set(2);
                    //把数据存储到沉默周期
                    redisTemplate.opsForValue().set(silentCacheKey,item.getValue()+"",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
                }


                redisTemplate.opsForValue().set(aggCountKey,1+"");
                redisTemplate.opsForValue().set(aggTimeKey,item.getTime()+"");
                return;
            }
            //判断上报时间是否超过聚合周期（上次的上报时间+聚合周期）
            LocalDateTime preTime = LocalDateTimeUtil.of(Long.parseLong(aggTimeData + "")).plusMinutes(alertRule.getDataAggregationPeriod());
            if(preTime.isAfter(LocalDateTimeUtil.of(item.getTime()))){
                return;
            }
            //累加次数
            int count = Integer.parseInt(aggCountData)+1;
            redisTemplate.opsForValue().set(aggCountKey,count+"");
            //判断次数是否与持续周期相等
            if(count != alertRule.getDuration()){
                redisTemplate.opsForValue().set(aggTimeKey,item.getTime()+"");
                return;
            }
            //相等  删除redis中的数据
            redisTemplate.delete(aggCountKey);
            redisTemplate.delete(aggTimeKey);

            //把数据存储到沉默周期
            redisTemplate.opsForValue().set(silentCacheKey,item.getValue()+"",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

            finalStatus.set(2);

        });

        return finalStatus.get();
    }

    private JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
        }

        @Override
        public void onSessionClosed(Session session, Throwable cause) {
        }

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
        }

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {
        }
    };

    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }
}